package com.yjh.auth.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.WebAttributes;
import org.springframework.web.bind.annotation.*;
import util.R;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
@RequestMapping("/users")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public Principal getUser(Principal principal) {
        logger.info("当前用户权限："+principal.toString());
        return principal;
    }


    @GetMapping("/login/error")
    @ResponseBody
    public R loginError(HttpServletRequest request) {
        AuthenticationException authenticationException = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

        R r = new R();
        r.setCode(201);
        if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
            r.setMsg("用户名或密码错误！");
        } else if (authenticationException instanceof DisabledException) {
            r.setMsg("用户已被禁用");
        } else if (authenticationException instanceof LockedException) {
            r.setMsg("账户被锁定");
        } else if (authenticationException instanceof AccountExpiredException) {
            r.setMsg("账户过期");
        } else if (authenticationException instanceof CredentialsExpiredException) {
            r.setMsg("证书过期");
        } else {
            r.setMsg("登录失败");
        }
        return r ;
    }

}